package com.gitee.pifeng.monitoring.ui.business.web.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.pifeng.monitoring.ui.business.web.annotation.OperateLog;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorEnv;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorFeed;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorGroup;
import com.gitee.pifeng.monitoring.ui.business.web.entity.MonitorUser;
import com.gitee.pifeng.monitoring.ui.business.web.realm.MonitorUserRealm;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorEnvService;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorFeedService;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorGroupService;
import com.gitee.pifeng.monitoring.ui.business.web.service.IMonitorUserService;
import com.gitee.pifeng.monitoring.ui.business.web.vo.LayUiAdminResultVo;
import com.gitee.pifeng.monitoring.ui.business.web.vo.MonitorFeedVo;
import com.gitee.pifeng.monitoring.ui.constant.OperateTypeConstants;
import com.gitee.pifeng.monitoring.ui.constant.UiModuleConstants;
import com.gitee.pifeng.monitoring.ui.constant.WebResponseConstants;
import com.gitee.pifeng.monitoring.ui.util.SpringSecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hyperic.sigar.SigarException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/monitor-feed")
@Api(tags = "运维单")
public class MonitorFeedController {

    /**
     * 监控环境服务类
     */
    @Autowired
    private IMonitorEnvService monitorEnvService;

    /**
     * 监控分组服务类
     */
    @Autowired
    private IMonitorGroupService monitorGroupService;
    @Autowired
    private IMonitorFeedService monitorFeedService;
    @Autowired
    private IMonitorUserService monitorUserService;


    public static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    public static final String accessKeyId = "LTAI5tGvxXsT1trR8qr9vyZy";
    public static final String accessKeySecret = "usYOXgOMwoKbIqmTrSoJSVe03R4NPe";
    public static final String bucketName = "feedimages";

    @ApiOperation(value = "访问运维单列表页面")
    @GetMapping("/list")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "访问运维单页面")
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView("feed/feed");
        // 监控环境列表
        List<String> monitorEnvs = this.monitorEnvService.list().stream().map(MonitorEnv::getEnvName).collect(Collectors.toList());
        // 监控分组列表
        List<String> monitorGroups = this.monitorGroupService.list().stream().map(MonitorGroup::getGroupName).collect(Collectors.toList());
        mv.addObject("monitorEnvs", monitorEnvs);
        mv.addObject("monitorGroups", monitorGroups);
        return mv;
    }

    @ApiOperation(value = "运维人员访问运维单列表页面")
    @GetMapping("/repairList")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "运维人员获取运维单页面")
    public ModelAndView repairList() {
        ModelAndView mv = new ModelAndView("feed/report-list");
        // 监控环境列表
        List<String> monitorEnvs = this.monitorEnvService.list().stream().map(MonitorEnv::getEnvName).collect(Collectors.toList());
        // 监控分组列表
        List<String> monitorGroups = this.monitorGroupService.list().stream().map(MonitorGroup::getGroupName).collect(Collectors.toList());
        mv.addObject("monitorEnvs", monitorEnvs);
        mv.addObject("monitorGroups", monitorGroups);
        return mv;
    }

    @ApiOperation(value = "普通用户访问运维单列表页面")
    @GetMapping("/commonList")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "普通用户获取运维单页面")
    public ModelAndView commonList() {
        ModelAndView mv = new ModelAndView("feed/appraise-list");
        // 监控环境列表
        List<String> monitorEnvs = this.monitorEnvService.list().stream().map(MonitorEnv::getEnvName).collect(Collectors.toList());
        // 监控分组列表
        List<String> monitorGroups = this.monitorGroupService.list().stream().map(MonitorGroup::getGroupName).collect(Collectors.toList());
        mv.addObject("monitorEnvs", monitorEnvs);
        mv.addObject("monitorGroups", monitorGroups);
        return mv;
    }

    @ApiOperation(value = "获取运维单列表")
    @GetMapping("/get-monitor-feed-list")
    @ResponseBody
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "获取运维单列表")
    public LayUiAdminResultVo getMonitorFeedList(Long current, Long size, String feedNumber, String submitUser, String solveUser, Integer status) {
        Page<MonitorFeedVo> page = this.monitorFeedService.getMonitorFeedList(current, size, feedNumber, submitUser, solveUser, status);
        return LayUiAdminResultVo.ok(page);
    }

    @ApiOperation(value = "运维人员获取运维单列表")
    @GetMapping("/repair-get-monitor-feed-list")
    @ResponseBody
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "运维人员获取运维单列表")
    public LayUiAdminResultVo repairGetMonitorFeedList(Long current, Long size, String feedNumber, String submitUser, Integer status) {
        MonitorUserRealm principal = (MonitorUserRealm) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Page<MonitorFeedVo> page = this.monitorFeedService.getRepairMonitorFeedList(current, size, feedNumber, status, principal.getUsrname(), submitUser);
        return LayUiAdminResultVo.ok(page);
    }

    @ApiOperation(value = "普通人员获取运维单列表")
    @GetMapping("/common-get-monitor-feed-list")
    @ResponseBody
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "普通人员获取运维单列表")
    public LayUiAdminResultVo commonGetMonitorFeedList(Long current, Long size, String feedNumber, String solveUser, Integer status) {
        MonitorUserRealm principal = (MonitorUserRealm) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Page<MonitorFeedVo> page = this.monitorFeedService.getCommonMonitorFeedList(current, size, feedNumber, status, principal.getUsrname(), solveUser);
        return LayUiAdminResultVo.ok(page);
    }

    @ApiOperation(value = "访问新增运维单页面")
    @GetMapping("/add-feed-form")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.PAGE, operDesc = "管理员获取运维单新增页面")
    public ModelAndView addFeedForm() {
        ModelAndView mv = new ModelAndView("feed/add-feed");
        return mv;
    }

    @ApiOperation(value = "访问新增运维单页面")
    @GetMapping("/new-feed-form")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.PAGE, operDesc = "普通用户获取运维单列表")
    public ModelAndView newFeedForm() {
        ModelAndView mv = new ModelAndView("feed/new-feed");
        return mv;
    }

    @ApiOperation(value = "进入运维评价页面")
    @GetMapping("/add-feed-appraise")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.PAGE, operDesc = "进入运维评价页面")
    public ModelAndView addFeedAppraiseForm() {
        ModelAndView mv = new ModelAndView("feed/appraise");
        return mv;
    }

    @ApiOperation(value = "上传运维单图片")
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
//    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.ADD, operDesc = "上传图片")
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam MultipartFile file) {
        Map<String, Object> mv = new HashMap<String, Object>();
        Map<String, String> mvv = new HashMap<String, String>();
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            Calendar date = Calendar.getInstance(); //Calendar.getInstance()是获取一个Calendar对象并可以进行时间的计算，时区的指定
            String originalFile = file.getOriginalFilename(); //获得文件最初的名字
            String uuid = UUID.randomUUID().toString();    //UUID转化为String对象
            String newfilename = date.get(Calendar.YEAR) + "" + (date.get(Calendar.MONTH) + 1) + "" + date.get(Calendar.DATE) + uuid.replace("-", "") + originalFile;
            InputStream inputStream = file.getInputStream();
            PutObjectResult putObjectResult = oss.putObject(bucketName, newfilename, inputStream);
            mvv.put("url", "https://" + bucketName + "." + endpoint + "/" + newfilename);
            mvv.put("atl", putObjectResult.getETag());
            mvv.put("href", "https://" + bucketName + "." + endpoint + "/" + newfilename);
            mv.put("erron", 0);
            System.out.println("上传成功");
            mv.put("data", mvv);
            return mv;
        } catch (IOException e) {
            e.printStackTrace();
            mv.put("erron", 1);
            mv.put("message", "上传失败");
            return mv;
        }

    }

    @ApiOperation(value = "提交运维单")
    @RequestMapping("/save_feed")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.ADD, operDesc = "提交运维单")
    @ResponseBody
    public LayUiAdminResultVo saveFeed(@RequestParam(value = "content") String content,
                                       @RequestParam(value = "title") String title,
                                       @RequestParam(value = "phone") String phone,
                                       @RequestParam(value = "email") String email) {
        MonitorFeed monitorFeed = new MonitorFeed();
        MonitorUserRealm principal = (MonitorUserRealm) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        monitorFeed.setSubmitUser(principal.getUsrname());
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String format1 = format.format(date);
        int i = (int) (Math.random() * 900 + 100);
        String s = Integer.toString(i);
        monitorFeed.setFeedNumber(format1 + i);
        monitorFeed.setSubmitTime(date);
        monitorFeed.setContent(content);
        monitorFeed.setFeedTitle(title);
        monitorFeed.setStatus(0);
        monitorFeed.setCantReport(0);
        monitorFeed.setPhone(phone);
        monitorFeed.setEmail(email);
        LayUiAdminResultVo layUiAdminResultVo = monitorFeedService.saveMonitorFeed(monitorFeed);
        return layUiAdminResultVo;
    }

    @ApiOperation(value = "获取运维单详情")
    @RequestMapping("/feed-detail")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "获取运维单详情")
    public ModelAndView feedDetail(@RequestParam(value = "id") String id) {
        MonitorFeedVo monitorFeedVo = monitorFeedService.getFeedDetail(id);
        ModelAndView modelAndView = new ModelAndView("feed/detail");
        modelAndView.addObject(monitorFeedVo);
        return modelAndView;
    }

    @ApiOperation(value = "删除运维单")
    @DeleteMapping("/delete-monitor-feed")
    @ResponseBody
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.DELETE, operDesc = "删除运维单")
    public LayUiAdminResultVo deleteFeed(@RequestBody List<MonitorFeedVo> monitorFeedVos) {
        return this.monitorFeedService.deleteFeed(monitorFeedVos);
    }

    @ApiOperation(value = "进入处理运维单页面")
    @GetMapping("/feed-handel")
    public ModelAndView feedHandelPage() {
        ModelAndView mv = new ModelAndView("feed/handel-feed");
        return mv;
    }

    @ApiOperation(value = "管理员指派运维单")
    @PostMapping("/edit-monitor-feed")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.UPDATE, operDesc = "管理员指派运维单")
    @ResponseBody
    public LayUiAdminResultVo editFeed(@RequestParam(value = "id") String id,
                                       @RequestParam(value = "dp") String dp) throws SigarException, IOException {
        MonitorUser monitorUser = monitorUserService.selectById(dp);
        MonitorFeed monitorFeed = monitorFeedService.selectByid(id);
        monitorFeed.setSolveUser(monitorUser.getUsername());
        monitorFeed.setStatus(1);
        monitorFeed.setDepartment(monitorUser.getDepartment());
        monitorFeedService.updateMonitorFeed(monitorFeed);
        //0为需要处理 1为处理完成
        monitorFeedService.sendFeedMail(monitorUser.getEmail(),"0");
        System.out.println(monitorFeed);
        return LayUiAdminResultVo.ok(WebResponseConstants.SUCCESS);
    }

    @ApiOperation(value = "完成运维单")
    @PostMapping("/close-monitor-feed")
    @ResponseBody
    public LayUiAdminResultVo closeFeed(@RequestBody MonitorFeed monitorFeed) throws SigarException, IOException {
        MonitorFeedVo feedDetail = monitorFeedService.getFeedDetail(String.valueOf(monitorFeed.getId()));
        feedDetail.setStatus(2);
        feedDetail.setSolveTime(new Date());
        MonitorFeed monitorFeed1 = new MonitorFeed();
        BeanUtils.copyProperties(feedDetail, monitorFeed1);
        monitorFeedService.updateMonitorFeed(monitorFeed1);
        monitorFeedService.sendFeedMail(feedDetail.getEmail(),"1");
        return LayUiAdminResultVo.ok(WebResponseConstants.SUCCESS);
    }

    @ApiOperation(value = "访问运维单报告填写页面")
    @GetMapping("/add-feed-report")
    public ModelAndView addFeedReport() {
        ModelAndView mv = new ModelAndView("feed/report");
        return mv;
    }

    @ApiOperation(value = "提交运维报告")
    @PutMapping("/save-report")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.ADD, operDesc = "提交运维报告")
    @ResponseBody
    public LayUiAdminResultVo saveReport(@RequestParam(value = "content") String content,
                                         @RequestParam(value = "id") String id) {
        Integer a = 1;
        return monitorFeedService.addReport(id, content, a);
    }

    @ApiOperation(value = "评价运维流程")
    @PutMapping("/save-appraise")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.ADD, operDesc = "评价运维流程")
    @ResponseBody
    public LayUiAdminResultVo saveAppraise(@RequestParam(value = "content") String content,
                                           @RequestParam(value = "id") String id) {
        MonitorFeedVo feedDetail = this.monitorFeedService.getFeedDetail(id);
        feedDetail.setAppraise(content);
        MonitorFeed monitorFeed = new MonitorFeed();
        BeanUtils.copyProperties(feedDetail, monitorFeed);
        this.monitorFeedService.updateMonitorFeed(monitorFeed);
        return LayUiAdminResultVo.ok(WebResponseConstants.SUCCESS);
    }

    @ApiOperation(value = "运维单统计")
    @GetMapping("/statistics")
    public ModelAndView statistics() {
        ModelAndView modelAndView = new ModelAndView("feed/avg-statistics1");
        return modelAndView;
    }

    @ApiOperation(value = "获取运维单数量统计数据")
    @GetMapping("/get-last7day-feed")
    @OperateLog(operModule = UiModuleConstants.Feed, operType = OperateTypeConstants.QUERY, operDesc = "获取运维单数量统计数据")
    @ResponseBody
    public LayUiAdminResultVo getLast7DayFeed() {
        return monitorFeedService.getLast7DayFeed();
    }

    @ApiOperation(value = "获取各个人员统计数据")
    @GetMapping("/get-user-feed")
    @ResponseBody
    public LayUiAdminResultVo getUserFeed() {
        return monitorFeedService.getUserFeed();
    }

    @ApiOperation(value = "按照部门统计数据")
    @GetMapping("/get-department-feed")
    @ResponseBody
    public LayUiAdminResultVo getFeedDepartment(){
        return monitorFeedService.getFeedDepartment();
    }

}
